<?php

namespace app\common;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\facade\Config;

class JwtTool
{
    /**
     * 生成 JWT Token
     * @param array $payload Token数据
     * @return string
     */
    public static function encode(array $payload): string
    {
        $key = self::getKey();
        $token = JWT::encode($payload, $key, 'HS256');
        return $token;
    }

    /**
     * 解析并验证 JWT Token
     * @param string $token
     * @return object|array
     * @throws \Exception
     */
    public static function decode(string $token)
    {
        $key = self::getKey();
        try {
            $decoded = JWT::decode($token, new Key($key, 'HS256'));
            return (array)$decoded;
        } catch (\Exception $e) {
            // token无效、过期、被篡改等
            throw new \Exception('Token无效或已过期');
        }
    }

    /**
     * 获取JWT密钥
     */
    private static function getKey(): string
    {
        // 从 config/jwt.php 中读取 key
        return Config::get('jwt.key');
    }
}